import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getPositions, getPosition, createPosition, updatePosition, deletePosition, getInterviews, getInterview, createInterview, updateInterview, deleteInterview, getResumes, getResume, createResume, updateResume, deleteResume } from '../api/recruitment'

// 职位相关异步操作
export const fetchPositions = createAsyncThunk(
  'recruitment/fetchPositions',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getPositions(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取职位列表失败' })
    }
  }
)

export const fetchPositionDetail = createAsyncThunk(
  'recruitment/fetchPositionDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getPosition(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取职位详情失败' })
    }
  }
)

export const addPosition = createAsyncThunk(
  'recruitment/addPosition',
  async (positionData, { rejectWithValue }) => {
    try {
      const response = await createPosition(positionData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加职位失败' })
    }
  }
)

export const editPosition = createAsyncThunk(
  'recruitment/editPosition',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updatePosition(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新职位失败' })
    }
  }
)

export const removePosition = createAsyncThunk(
  'recruitment/removePosition',
  async (id, { rejectWithValue }) => {
    try {
      await deletePosition(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除职位失败' })
    }
  }
)

// 面试相关异步操作
export const fetchInterviews = createAsyncThunk(
  'recruitment/fetchInterviews',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getInterviews(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取面试列表失败' })
    }
  }
)

export const fetchInterviewDetail = createAsyncThunk(
  'recruitment/fetchInterviewDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getInterview(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取面试详情失败' })
    }
  }
)

export const addInterview = createAsyncThunk(
  'recruitment/addInterview',
  async (interviewData, { rejectWithValue }) => {
    try {
      const response = await createInterview(interviewData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加面试失败' })
    }
  }
)

export const editInterview = createAsyncThunk(
  'recruitment/editInterview',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateInterview(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新面试失败' })
    }
  }
)

export const removeInterview = createAsyncThunk(
  'recruitment/removeInterview',
  async (id, { rejectWithValue }) => {
    try {
      await deleteInterview(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除面试失败' })
    }
  }
)

// 简历相关异步操作
export const fetchResumes = createAsyncThunk(
  'recruitment/fetchResumes',
  async (params, { rejectWithValue }) => {
    try {
      const response = await getResumes(params)
      return response
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取简历列表失败' })
    }
  }
)

export const fetchResumeDetail = createAsyncThunk(
  'recruitment/fetchResumeDetail',
  async (id, { rejectWithValue }) => {
    try {
      const response = await getResume(id)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '获取简历详情失败' })
    }
  }
)

export const addResume = createAsyncThunk(
  'recruitment/addResume',
  async (resumeData, { rejectWithValue }) => {
    try {
      const response = await createResume(resumeData)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '添加简历失败' })
    }
  }
)

export const editResume = createAsyncThunk(
  'recruitment/editResume',
  async ({ id, data }, { rejectWithValue }) => {
    try {
      const response = await updateResume(id, data)
      return response.data
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '更新简历失败' })
    }
  }
)

export const removeResume = createAsyncThunk(
  'recruitment/removeResume',
  async (id, { rejectWithValue }) => {
    try {
      await deleteResume(id)
      return id
    } catch (error) {
      return rejectWithValue(error.response?.data || { message: '删除简历失败' })
    }
  }
)

const initialState = {
  // 职位相关状态
  positions: [],
  currentPosition: null,
  positionPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 面试相关状态
  interviews: [],
  currentInterview: null,
  interviewPagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 简历相关状态
  resumes: [],
  currentResume: null,
  resumePagination: {
    current: 1,
    pageSize: 10,
    total: 0
  },
  // 通用状态
  loading: false,
  error: null,
  // 统计数据
  statistics: {
    openPositions: 0,
    totalApplications: 0,
    pendingInterviews: 0,
    hiredCandidates: 0
  }
}

const recruitmentSlice = createSlice({
  name: 'recruitment',
  initialState,
  reducers: {
    clearError: (state) => {
      state.error = null
    },
    // 职位分页设置
    setPositionCurrentPage: (state, action) => {
      state.positionPagination.current = action.payload
    },
    setPositionPageSize: (state, action) => {
      state.positionPagination.pageSize = action.payload
    },
    clearCurrentPosition: (state) => {
      state.currentPosition = null
    },
    // 面试分页设置
    setInterviewCurrentPage: (state, action) => {
      state.interviewPagination.current = action.payload
    },
    setInterviewPageSize: (state, action) => {
      state.interviewPagination.pageSize = action.payload
    },
    clearCurrentInterview: (state) => {
      state.currentInterview = null
    },
    // 简历分页设置
    setResumeCurrentPage: (state, action) => {
      state.resumePagination.current = action.payload
    },
    setResumePageSize: (state, action) => {
      state.resumePagination.pageSize = action.payload
    },
    clearCurrentResume: (state) => {
      state.currentResume = null
    }
  },
  extraReducers: (builder) => {
    builder
      // 职位相关状态处理
      .addCase(fetchPositions.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchPositions.fulfilled, (state, action) => {
        state.loading = false
        state.positions = action.payload.data || []
        state.positionPagination.total = action.payload.total || 0
        if (action.payload.statistics) {
          state.statistics.openPositions = action.payload.statistics.openPositions || 0
        }
      })
      .addCase(fetchPositions.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取职位列表失败'
      })
      .addCase(fetchPositionDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchPositionDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentPosition = action.payload
      })
      .addCase(fetchPositionDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取职位详情失败'
      })
      .addCase(addPosition.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addPosition.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addPosition.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加职位失败'
      })
      .addCase(editPosition.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editPosition.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editPosition.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新职位失败'
      })
      .addCase(removePosition.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removePosition.fulfilled, (state, action) => {
        state.loading = false
        state.positions = state.positions.filter(position => position.id !== action.payload)
      })
      .addCase(removePosition.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除职位失败'
      })

      // 面试相关状态处理
      .addCase(fetchInterviews.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchInterviews.fulfilled, (state, action) => {
        state.loading = false
        state.interviews = action.payload.data || []
        state.interviewPagination.total = action.payload.total || 0
        if (action.payload.statistics) {
          state.statistics.pendingInterviews = action.payload.statistics.pendingInterviews || 0
        }
      })
      .addCase(fetchInterviews.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取面试列表失败'
      })
      .addCase(fetchInterviewDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchInterviewDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentInterview = action.payload
      })
      .addCase(fetchInterviewDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取面试详情失败'
      })
      .addCase(addInterview.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addInterview.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addInterview.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加面试失败'
      })
      .addCase(editInterview.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editInterview.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editInterview.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新面试失败'
      })
      .addCase(removeInterview.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeInterview.fulfilled, (state, action) => {
        state.loading = false
        state.interviews = state.interviews.filter(interview => interview.id !== action.payload)
      })
      .addCase(removeInterview.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除面试失败'
      })

      // 简历相关状态处理
      .addCase(fetchResumes.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchResumes.fulfilled, (state, action) => {
        state.loading = false
        state.resumes = action.payload.data || []
        state.resumePagination.total = action.payload.total || 0
        if (action.payload.statistics) {
          state.statistics.totalApplications = action.payload.statistics.totalApplications || 0
        }
      })
      .addCase(fetchResumes.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取简历列表失败'
      })
      .addCase(fetchResumeDetail.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(fetchResumeDetail.fulfilled, (state, action) => {
        state.loading = false
        state.currentResume = action.payload
      })
      .addCase(fetchResumeDetail.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '获取简历详情失败'
      })
      .addCase(addResume.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(addResume.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(addResume.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '添加简历失败'
      })
      .addCase(editResume.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(editResume.fulfilled, (state) => {
        state.loading = false
      })
      .addCase(editResume.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '更新简历失败'
      })
      .addCase(removeResume.pending, (state) => {
        state.loading = true
        state.error = null
      })
      .addCase(removeResume.fulfilled, (state, action) => {
        state.loading = false
        state.resumes = state.resumes.filter(resume => resume.id !== action.payload)
      })
      .addCase(removeResume.rejected, (state, action) => {
        state.loading = false
        state.error = action.payload?.message || '删除简历失败'
      })
  }
})

export const { 
  clearError, 
  setPositionCurrentPage, 
  setPositionPageSize, 
  clearCurrentPosition,
  setInterviewCurrentPage,
  setInterviewPageSize,
  clearCurrentInterview,
  setResumeCurrentPage,
  setResumePageSize,
  clearCurrentResume
} = recruitmentSlice.actions

export default recruitmentSlice.reducer